//linkedList.c

#include "linkedList.h"
#include "unistd.h"

LIST* createList(){
  LIST *list=(LIST*)calloc(1,24);
  CHECK_ALC_ERROR(list);
  list->first=NULL;
  list->size=0;
  return list;
}

void addEl(LIST *list, void *val){
  //alloc pointer
  EL *curr= (EL *)calloc(1,16);
  CHECK_ALC_ERROR(curr);
  curr->val=val;
  
  if(list->first==NULL){
    list->first=curr;
    list->last=list->first;
  }
  else{
    //link to last node
  list->last->next=curr;
  //make new node last node
  list->last=curr;
  }
  list->size++;
}
void* removeFirst(LIST *list){
  if(list->size==0){
    return NULL;
  }
  EL *curr=list->first;
  char* val=curr->val;
  list->first=curr->next;
  free(curr);
  list->size--;
  return (void*)val;
}
int getSize(LIST *list){
  return list->size;
}

void** getArray(LIST *list){
  int i;
  EL *curr=list->first;
  EL *temp;
  //size +1 for null pointer
  void** array=calloc(list->size+1,8); 
  CHECK_ALC_ERROR(array);

  //loop from beggining to end to output array in order elements were inserted
  for(i=0;i<list->size;i++){
    array[i]=curr->val;
    temp=curr;
    curr=curr->next;
    free(temp);
  }
  //null terminated
  array[list->size]=NULL;
  list->first=NULL;
  list->last=NULL;
  list->size=0;
  return array;
}

/*
//for debugging linked list
int main(int argc,char* argv[],char* envp[]){
  LIST *ls=createList();
  addEl(ls,"ONE");
  addEl(ls,"TWO");
addEl(ls,"THREE");
//getArray(ls);
 while(removeFirst(ls)!=NULL);
  
}
*/












